package com.framework.loippi.controller.api;


import com.framework.loippi.api.utils.ApiUtils;
import com.framework.loippi.cache.ConfigCache;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;

public class ApiBaseController {


    protected final Logger logger = LoggerFactory.getLogger(getClass());

    public static final String[] ignoreExceptionMessages = new String[]{
            "你的主机中的软件中止了一个已建立的连接。",
            "Broken pipe",
            "断开的管道",
            "Your request params is invalid. Please check them according to error message."
    };

    public boolean ignoreExcepionMessage(String message) {
        for (String iem : ignoreExceptionMessages) {
            if (message.contains(iem))
                return true;
        }
        return false;
    }

    /**
     * 用于处理异常的
     *
     * @return
     */
    @ExceptionHandler({Exception.class})
    public @ResponseBody
    String Exception(Exception e, HttpServletRequest request) {

        String message = e.getMessage();

        if(ignoreExcepionMessage(message)){
            logger.warn("系统错误[" + request.getRequestURI() + "]", e);
        }else{
            logger.error("系统错误[" + request.getRequestURI() + "]", e);
        }

        if ("prod".equals(ConfigCache.getConfig("env"))) {
            return ApiUtils.error("非法操作，服务器异常");
        }

        return ApiUtils.error("系统错误：" + message);
    }

}
